package com.zsc.oj.judge;

import cn.hutool.json.JSONUtil;
import com.zsc.oj.common.ErrorCode;
import com.zsc.oj.exception.BusinessException;
import com.zsc.oj.judge.codesandbox.CodeSendBox;
import com.zsc.oj.judge.codesandbox.CodeSendBoxFactory;
import com.zsc.oj.judge.codesandbox.CodeSendBoxProxy;
import com.zsc.oj.judge.codesandbox.model.ExecuteCodeRequest;
import com.zsc.oj.judge.codesandbox.model.ExecuteCodeResponse;
import com.zsc.oj.judge.strategy.JudgeContext;
import com.zsc.oj.judge.strategy.JudgeManager;
import com.zsc.oj.model.dto.question.JudgeCase;
import com.zsc.oj.model.dto.questionSubmit.JudgeInfo;
import com.zsc.oj.model.entity.Question;
import com.zsc.oj.model.entity.QuestionSubmit;
import com.zsc.oj.model.enums.QuestionSubmitStatusEnum;
import com.zsc.oj.service.QuestionService;
import com.zsc.oj.service.QuestionSubmitService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 判题服务实现类
 */
@Service
public class JudgeServiceImp implements JudgeService{
    @Value("${CodeSendBox.type:example}")
    private String type;

    @Resource
    private QuestionService questionService;

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private JudgeManager judgeManager;

    @Override
    public QuestionSubmit doJudge(long questionSubmitId) {

        //1、传入用户提交题目的id获取到对应的`QuestionSubmit`，并提取出code和language

        QuestionSubmit questionSubmit = questionSubmitService.getById(questionSubmitId);
        String code = questionSubmit.getCode();
        String language = questionSubmit.getLanguage();


        if(questionSubmit == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        Question question = questionService.getById(questionId);
        if(question == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目不存在");
        }

        //从题目中获取输出用例
        String judgeCase = question.getJudgeCase();
        List<JudgeCase> judgeCaseList = JSONUtil.toList(judgeCase, JudgeCase.class);
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());

        //2、如果题目状态不为判题中，就不用重复执行。
        Integer status = questionSubmit.getStatus();
        if(!status.equals(QuestionSubmitStatusEnum.WAITING.getValue())){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目正在判题中");
        }

        //3、更改判题的状态为判题中
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmit.getId());
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.JUDGING.getValue());
        boolean update = questionSubmitService.updateById(questionSubmitUpdate);
        if(!update){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"判题更新失败");
        }

        //4、调用沙箱，获取到执行结果
        CodeSendBox codeSendBox = CodeSendBoxFactory.newInstance(type);
        codeSendBox = new CodeSendBoxProxy(codeSendBox);
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(code)
                .inputList(inputList)
                .language(language)
                .build();
        ExecuteCodeResponse executeCodeResponse = codeSendBox.ExecuteCode(executeCodeRequest);

        //5、根据沙箱的执行结果修改题目的判题状态和信息
        JudgeContext judgeContext = new JudgeContext();
        judgeContext.setJudgeInfo(executeCodeResponse.getJudgeInfo());
        judgeContext.setInputList(inputList);
        judgeContext.setOutputList(executeCodeResponse.getOutputList());
        judgeContext.setQuestion(question);
        judgeContext.setJudgeCaseList(judgeCaseList);
        judgeContext.setQuestionSubmit(questionSubmit);

        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);

        //6、修改数据库中的判题结果
        questionSubmitUpdate = new QuestionSubmit();
        questionSubmitUpdate.setId(questionSubmitId);
        questionSubmitUpdate.setStatus(QuestionSubmitStatusEnum.SUCCESS.getValue());
        questionSubmitUpdate.setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));

        boolean update2 = questionSubmitService.updateById(questionSubmitUpdate);
        if(!update2){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"判题更新失败");
        }
        QuestionSubmit questionSubmitResponse = questionSubmitService.getById(questionSubmitId);
        return questionSubmitResponse;
    }
}
